/*		<one line to give the program's name and a brief idea of what it does.>
* Copyright (C) <2025>  <zhen>
* 
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* 
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
* 
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <https://www.gnu.org/licenses/>.
* */

#include "can/Xcanmsg.h"
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <time.h>
#ifdef __WIN32
#include <windows.h>
#endif

#if defined(__MINGW32__) || defined(__MINGW64__)
#define gettimeofday(p,z) mingw_gettimeofday(p,z)
#endif

struct canMsgMail *testmail;

void *thread_fun(void *arg){
    canMsg_t msgr;
    memset(&msgr,0,sizeof(canMsg_t));
    printf("发送线程就绪\r\n");
    for(int i = 0;i < 5;i++){
        msgr.ID = 0x100 + i;
        msgr.DLC = 8;
        for(int j = 0;j < 8;j++){
            msgr.Data[j] = j+i;
        }
        gettimeofday(&msgr.tv,NULL);
        sendCanMsg(testmail,&msgr);
        printf("发送成功\r\n");
        usleep(500*1000);
    }
    for(int i = 0;i < 5;i++){
        msgr.ID = 0x100 + i;
        msgr.DLC = len2dlc(64);
        msgr.FDF = 1;
        msgr.IDE = 1;
        for(int j = 0;j < 64;j++){
            msgr.Data[j] = j+i;
        }
        gettimeofday(&msgr.tv,NULL);
        sendCanMsg(testmail,&msgr);
        printf("发送成功\r\n");
        usleep(500*1000);
    }
    sleep(3);
    return NULL;
}


int main(int argc, char *argv[])
{
#ifdef __WIN32
    // 设置控制台utf8
    SetConsoleOutputCP(CP_UTF8);
#endif
    pthread_t threadid;
    testmail = createCanMsgMail();
    // 创建线程
    if(pthread_create(&threadid,NULL,thread_fun,NULL) != 0){
        perror("线程创建失败");
        return -1;
    }
    canMsg_t msgr;
    for(int i = 0;i < 10;i++){
        printf("开始接收can数据\n");
        if(rescvCanMsg(testmail,&msgr,1000) == X_ok){
            printf("接收成功\r\n");
            dumpCanMsg(stdout, &msgr);
        }else{
            printf("接收超时\r\n");
        }
        
    }
    pthread_join(threadid,NULL);
    destroyCanMsgMail(testmail);
    printf("所有线程结束\r\n");
    // dumpCanMsg(stdout, &testmsg);
    return 0;
}